import React, {Component} from 'react';
import {Card, Alert, Typography, DatePicker} from 'antd';
import {connect} from 'dva';
import * as echart from 'echarts';
import {addResizeHook} from '@/utils/resize';
import {trigger} from "@/utils/utils";
import moment from "moment";
import time, {convertDateFromString, dateFormat} from "@/utils/time";
import {getLatestTime} from "@/services/indicator";

const {RangePicker} = DatePicker;

// 通用的图表
class Common extends Component {
  stopLoop = false;

  state = {
    option: {
      grid: {
        left: '1%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      title: {
        text: '',
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: [],
      },
      series: [],
    },
  };

  async componentDidMount() {
    const {name, dispatch, stopLoop,timeRange=1} = this.props;
    const {option} = this.state;
    // this.props.dispatch({
    //   type: 'indicator/chart',
    //   payload: { name },
    // });
    const resp = await getLatestTime({
      itemName: name,
    });
    const {start,end,current} = resp.detail
    let startTime = convertDateFromString(start)
    let endTime = convertDateFromString(end)
    let currentTime = convertDateFromString(current)

    this.stopLoop = stopLoop;
    const selectedStartTime = time.minusDay(startTime,timeRange)
    const selectedEndTime = endTime

    this.chartRef = requestAnimationFrame(() =>
      trigger(
        () => {
          dispatch({
            type: 'indicator/chart',
            payload: {
              name,
              start: dateFormat(selectedStartTime),
              end: dateFormat(selectedEndTime)
            },
          });
        },
        new Date().valueOf(),
        20000,
        true,
        () => false,
      ),
    );

    const chart = echart.init(document.getElementById(name));
    chart.setOption(option);
    this.setState({chart,selectedStartTime,selectedEndTime});

    addResizeHook(this, chart.resize);
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.chartRef);
    this.stopLoop = true;
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const {indicator, name} = nextProps;
    const {option, chart} = prevState;

    const chartData = indicator[name];

    // 当传入的type发生变化的时候，更新state
    if (chart && chartData && chartData !== prevState.chartData) {
      option.series = [];

      if (chartData.yAxis_array) {
        option.yAxis = [];
        for (const element of chartData.yAxis_array) {
          option.yAxis.push(element);
        }
      }

      if (chartData.legend) {
        option.legend = chartData.legend
      }

      option.radar = chartData.radar
      option.tooltip = chartData.tooltip

      if (chartData.y_array) {
        for (const element of chartData.y_array) {
          option.series.push({
            showSymbol: false,
            name: element.name,
            data: element.y,
            type: element.type,
            tooltip: element.tooltip,
            color: element.color,
            markPoint: element.markPoint,
            markLine: element.markLine,
            yAxisIndex: element.yAxisIndex,
            lineStyle: {
              type: element.lineStyle,
            },
          });
        }
      }
      option.title.text = chartData.desc;
      if (chartData.x) {
        option.xAxis = {
          type: 'category',
          data : chartData.x
        }
      }

      chart.setOption(option, true);
      return {chartData};
    }
    return null;
  }

  timePick = value => {
    this.state.selectedStartTime = value[0].toDate();
    this.state.selectedEndTime = value[1].toDate();
    const {name, dispatch} = this.props
    dispatch({
      type: 'indicator/chart',
      payload: {
        name,
        start: dateFormat(value[0].toDate()),
        end: dateFormat(value[1].toDate())
      },
    });
  };

  render() {
    const dtFormat = 'YYYY-MM-DD HH';
    const {selectedStartTime, selectedEndTime} = this.state;
    const {width = 100, height = 350, name,useDatePicker=true} = this.props;
    return (
      <Card>
        {useDatePicker &&<RangePicker
          key={Math.random()} //强制刷新组件
          style={{width: 300}}
          showTime={{format: 'HH'}}
          format={dtFormat}
          placeholder={['开始时间', '结束时间']}
          onOk={this.timePick}
          defaultValue={[moment(selectedStartTime, dtFormat), moment(selectedEndTime, dtFormat)]}
        />}
        <div id={name} style={{width: `${width}%`, height}}/>
      </Card>
    );
  }
}

export default connect(({indicator, global}) => ({
  indicator,
  global,
}))(Common);
